package com.quick.api.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author ：chicunxiang
 * @date ：Created in 2021/3/25 13:54
 * @description：
 * @version: 1.0
 */
@Aspect
@Order(-10)
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(DataSourceAnnotation)")
    public void before(JoinPoint point) {
        Class<?> clazz = point.getTarget().getClass();
        MethodSignature signature = (MethodSignature) point.getSignature();
        try {
            Method method = clazz.getMethod(signature.getName(), signature.getParameterTypes());
            if (method.isAnnotationPresent(DataSourceAnnotation.class)) {
                // 根据注解设置数据源
                DataSourceAnnotation annotation = method.getAnnotation(DataSourceAnnotation.class);
                // 执行前. 切换到数据源.
                DynamicDataSourceContextHolder.setDataSource(annotation.value());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @After("@annotation(DataSourceAnnotation)")
    public void after(JoinPoint point) {
        DynamicDataSourceContextHolder.setDefaultDataSource();
    }
}